//
//  PlayerViewController.m
//  HeartFM
//
//  Created by qianfeng on 15/11/3.
//  Copyright (c) 2015年 Lishukang. All rights reserved.
//
#import "PlayerViewController.h"

@interface PlayerViewController ()<AudioPlayerDelegate>

@property (nonatomic,strong) UIBarButtonItem *rightBarButtonItem;

@end

@implementation PlayerViewController

+ (PlayerViewController *)sharePlayer{
    static PlayerViewController *sharePlayer;
    @synchronized(self) {
        if(sharePlayer == nil) {
            sharePlayer = [[[self class] alloc] init];
        }
    }
    return sharePlayer;
}

- (instancetype)init{
    if (self = [super init]) {
        //定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update:) userInfo:nil repeats:YES];
        [self.timer setFireDate:[NSDate distantFuture]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[UIFont systemFontOfSize:15],UITextAttributeFont,nil]];
    self.title = @"心灵之音";
    
    [self subViewSetting];
}

- (void)navigationItemSetting{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[[UIImage imageNamed: @"white_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed: @"down_big"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(non)];
    
    
//    NSArray *arr = [CollectionModel MR_findByAttribute:@"currentMp3Url" withValue:self.currentMp3Url];
//    if (arr.count == 0) {
//        self.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed: @"clolect_0"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(collect:)];
//    } else{
        self.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed: @"collect_1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(collect:)];
//    }
//    
    self.navigationItem.rightBarButtonItems = @[rightItem1,self.rightBarButtonItem];
}

- (void)non{
    
//    if (!self.currentMp3Url) {
//        NSLog(@"无节目");
//        return;
//    }
//    
//    NSArray *arr = [DownLoadModel MR_findByAttribute:@"currentMp3Url" withValue:self.currentMp3Url];
//    if (arr.count == 0) {
//        NSLog(@"下载节目");
//        DownLoadModel *model = [DownLoadModel MR_createEntity];
//        
//        model.currentMp3Url = self.currentMp3Url;
//        model.mainImageUrl = self.mainImageUrl;
//        model.topicTitle = self.topicTitle;
//        model.viewNum = self.viewNum;
//        model.avaImageUrl = self.avaImageUrl;
//        model.speakNickName = self.speakNickName;
//        model.md5Url = [model.currentMp3Url MD5Hash];
//        
//        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
//        [[[DownLoadViewController alloc] init] downLoadWithModel:model];
//    }else{
//        NSLog(@"已下载");
//    }
}

- (void)collect:(UIBarButtonItem *)item{
//    if (self.currentMp3Url != nil) {
//        NSArray *arr = [CollectionModel MR_findByAttribute:@"currentMp3Url" withValue:self.currentMp3Url];
//        if (arr.count == 0) {
//            CollectionModel *collectionModel = [CollectionModel MR_createEntity];
//            
//            collectionModel.currentMp3Url = self.currentMp3Url;
//            collectionModel.mainImageUrl = self.mainImageUrl;
//            collectionModel.topicTitle = self.topicTitle;
//            collectionModel.viewNum = self.viewNum;
//            collectionModel.avaImageUrl = self.avaImageUrl;
//            collectionModel.speakNickName = self.speakNickName;
//            
//            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
//            item.image = [UIImage imageNamed: @"collect_1"];
//        } else{
//            for (CollectionModel *collectionModel in arr) {
//                [collectionModel MR_deleteEntity];
//            }
//            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
//            item.image = [UIImage imageNamed: @"clolect_0"];
//        }
//    }
}

- (void)back{
    [UIView  beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelay:0.1];
    [self.navigationController popViewControllerAnimated:NO];
    [UIView commitAnimations];
}

- (void)playWithUrl:(NSString *)Mp3url{
    if (!self.audioPlayer) {
        self.audioPlayer = [[AudioPlayer alloc] init];
        self.audioPlayer.delegate = self;
    }
    //判断是否有本地文件
//    NSString *md5str = [Mp3url MD5Hash];
//    NSArray *arr = [DownLoadModel MR_findByAttribute:@"md5Url" withValue:md5str];
//    if (arr.count != 0) {
//        DownLoadModel *downLoadModel = arr[0];
//        if ([downLoadModel.loadedSize doubleValue] == [downLoadModel.fileSize doubleValue]) {
//            NSLog(@"本地播放");
//            NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",md5str];
//            if (![Mp3url isEqualToString:self.currentMp3Url]) {
//                [self.audioPlayer stop];
//                self.currentMp3Url = Mp3url;
//                [self.audioPlayer play:[NSURL fileURLWithPath:path]];
//                return;
//            }else{
//                if ([PlayerViewController sharePlayer].audioPlayer.state == 8 || [PlayerViewController sharePlayer].audioPlayer.state == 5) {
//                    [self.audioPlayer stop];
//                    self.currentMp3Url = Mp3url;
//                    [self.audioPlayer play:[NSURL fileURLWithPath:path]];
//                }else {
//                    return;
//                }
//            }
//        }else{
//            [self.timer setFireDate:[NSDate distantPast]];
//            [self playThroughNet:Mp3url];
//        }
//    }else{
        [self.timer setFireDate:[NSDate distantPast]];
        [self playThroughNet:Mp3url];
    
    //监听是否中断
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleInterrupt:) name:AVAudioSessionInterruptionNotification object:nil];
    
//    }
}
#pragma mark - 监听到中断- 打电话
- (void)handleInterrupt:(NSNotification*)notification{
    NSLog(@"Interruption notification name %@", notification.name);
    
    if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
        NSLog(@"Interruption notification received %@!", notification);
        if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
            NSLog(@"Interruption began!");
        } else if([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeEnded]]){
            [self.audioPlayer stop];
        }
    }
}


- (void)playThroughNet:(NSString *)Mp3url{
    NSLog(@"网络播放");
    //判断是否为同一个节目
    if (![Mp3url isEqualToString:self.currentMp3Url]) {
        [self.audioPlayer stop];
        [self.audioPlayer play:[NSURL URLWithString:Mp3url]];
        self.currentMp3Url = Mp3url;
    }else{
        if ([PlayerViewController sharePlayer].audioPlayer.state == 8 || [PlayerViewController sharePlayer].audioPlayer.state == 5) {
            [self.audioPlayer stop];
            [self.audioPlayer play:[NSURL URLWithString:Mp3url]];
            self.currentMp3Url = Mp3url;
        }else {
            return;
        }
    }
}

#pragma mark - 子视图设置
- (void)subViewSetting{
    self.view.backgroundColor = [UIColor blackColor];
    //主图片
    self.mainImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-10-50-10-30-10-25-64)];
    self.mainImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.mainImageView];
    //渐变透明度图片
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-10-50-10-30-10-25-64)];
    backImageView.image = [UIImage imageNamed: @"launch_logo_bg"];
    [self.view addSubview:backImageView];
    
    //图片下背景图片
    self.bottomBackImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-10-50-10-30-10-25-64, self.view.bounds.size.width, self.view.bounds.size.height-self.view.bounds.size.width)];
    self.bottomBackImageView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.bottomBackImageView];
    //图片模糊化处理
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEffectView.frame = self.bottomBackImageView.frame;
    visualEffectView.alpha = 1.0;
    [self.view addSubview:visualEffectView];
    //暗化处理
    UIView *lightView = [[UIView alloc] initWithFrame:self.bottomBackImageView.frame];
    lightView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [self.view addSubview:lightView];
    
    //主题标签
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.view.bounds.size.height-10-50-10-30-10-25-20-30-64, self.view.bounds.size.width-5, 30)];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.titleLabel.textColor = [UIColor whiteColor];
    if (self.topicTitle == NULL) {
        self.topicTitle = @"主题";
    }
    [self.view addSubview:self.titleLabel];
    
    //收听量标签
    self.viewNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width-105, self.view.bounds.size.height-10-50-10-30-10-25-20-64, 100, 20)];
    self.viewNumLabel.font = [UIFont systemFontOfSize:12];
    self.viewNumLabel.textColor = [UIColor whiteColor];
    self.viewNumLabel.textAlignment = NSTextAlignmentRight;
    if (self.viewNum == NULL) {
        self.topicTitle = @"未知";
    }
    [self.view addSubview:self.viewNumLabel];
    
    //播放按钮
    self.playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.playButton.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height-10-50-10-30-5-64);
    if (self.isPlaying == YES) {
        [self.playButton setImage:[UIImage imageNamed: @"_pause"] forState:UIControlStateNormal];
    }else{
        [self.playButton setImage:[UIImage imageNamed: @"_play"] forState:UIControlStateNormal];
    }
    [self.playButton addTarget:self action:@selector(startPlay:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playButton];
    //后退按钮
    self.preButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    self.preButton.center = CGPointMake(self.view.bounds.size.width/4, self.view.bounds.size.height-10-50-10-30-5-64);
    [self.preButton setImage:[UIImage imageNamed: @"_pre"] forState:UIControlStateNormal];
    [self.preButton addTarget:self action:@selector(preClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.preButton];
    //前进按钮
    self.nextButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    self.nextButton.center = CGPointMake(self.view.bounds.size.width/4 * 3, self.view.bounds.size.height-10-50-10-30-5-64);
    [self.nextButton setImage:[UIImage imageNamed: @"_next"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextButton];
    
    //剩余时间标签
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width-110, self.view.bounds.size.height-10-50-10-30-64, 100, 30)];
    self.timeLabel.font = [UIFont systemFontOfSize:11];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentRight;
    self.timeLabel.text = @"未知";
    [self.view addSubview:self.timeLabel];
    
    //滑动条
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
    self.slider.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height-10-50-10-64);
    [self.slider setThumbImage:[UIImage imageNamed: @"slider_thumb"] forState:UIControlStateNormal];
    self.slider.tintColor = [UIColor orangeColor];
    [self.slider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    
    //主播头像
    self.avaImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, self.view.bounds.size.height-10-50-64, 50, 50)];
    self.avaImageView.layer.masksToBounds = YES;
    self.avaImageView.layer.cornerRadius = 25;
    [self.view addSubview:self.avaImageView];
    
    //主播名字
    self.speakNickNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, self.view.bounds.size.height-10-30-64, 100, 30)];
    self.speakNickNameLabel.font = [UIFont systemFontOfSize:13];
    self.speakNickNameLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:self.speakNickNameLabel];
}

- (void)update:(NSTimer *)timer{
    self.slider.value = self.audioPlayer.progress / self.audioPlayer.duration;
    self.timeLabel.text = [self currentTime];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationRepeatCount:1];
    self.avaImageView.transform = CGAffineTransformRotate(self.avaImageView.transform, M_PI/40);
    [UIView commitAnimations];
}

- (NSString *)currentTime{
    NSInteger minute = ((NSInteger)self.audioPlayer.duration - (NSInteger)self.audioPlayer.progress) / 60;
    NSInteger second = ((NSInteger)self.audioPlayer.duration - (NSInteger)self.audioPlayer.progress) % 60;
    NSString *currentTime = [NSString stringWithFormat:@"-%.2ld:%.2ld",minute,second];
    return currentTime;
}

- (void)valueChange:(UISlider *)slider{
    [self.audioPlayer seekToTime:self.slider.value * self.audioPlayer.duration];
}

- (void)startPlay:(UIButton *)playButton{
    if (self.currentMp3Url == NULL) {
        return;
    }
    if (self.isPlaying == NO) {
        self.isPlaying = YES;
        [self.timer setFireDate:[NSDate distantPast]];
        [self.audioPlayer resume];
        [self.playButton setImage:[UIImage imageNamed: @"_pause"] forState:UIControlStateNormal];
        if (self.audioPlayer.state == 8) {
            [self.audioPlayer play:[NSURL URLWithString:self.currentMp3Url]];
        }
    }else{
        self.isPlaying = NO;
        [self.timer setFireDate:[NSDate distantFuture]];
        [self.audioPlayer pause];
        [self.playButton setImage:[UIImage imageNamed: @"_play"] forState:UIControlStateNormal];
    }
}

- (void)preClick:(UIButton *)playButton{
    float preTime = self.audioPlayer.progress - self.audioPlayer.duration * 0.05;
    if (preTime < 0.0) {
        preTime = 0;
    }
    [self.audioPlayer seekToTime:preTime];
}

- (void)nextClick:(UIButton *)playButton{
    float nextTime = self.audioPlayer.progress + self.audioPlayer.duration * 0.05;
    if (nextTime > self.audioPlayer.duration) {
        nextTime = self.audioPlayer.duration;
    }
    [self.audioPlayer seekToTime:nextTime];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.mainImageView sd_setImageWithURL:[NSURL URLWithString:self.mainImageUrl] placeholderImage:[UIImage imageNamed: @"placehold_wide"]];
    [self.bottomBackImageView sd_setImageWithURL:[NSURL URLWithString:self.avaImageUrl] placeholderImage:[UIImage imageNamed: @"placehold_wide"]];
    self.titleLabel.text = self.topicTitle;
    self.viewNumLabel.text = [NSString stringWithFormat:@"收听  %@",self.viewNum];
    [self.avaImageView sd_setImageWithURL:[NSURL URLWithString:self.avaImageUrl] placeholderImage:[UIImage imageNamed: @"placehold_rec"]];
    self.speakNickNameLabel.text = self.speakNickName;
    
    [self navigationItemSetting];
}

- (void)pushPlayViewController{
    [self.view.window.rootViewController.navigationController pushViewController:[PlayerViewController sharePlayer] animated:YES];
}

#pragma mark - audioPlayer代理
//状态改变 进行处理
-(void) audioPlayer:(AudioPlayer*)audioPlayer stateChanged:(AudioPlayerState)state{
    if ([PlayerViewController sharePlayer].audioPlayer.state == 3) {
        self.isPlaying = YES;
        [self.timer setFireDate:[NSDate distantPast]];
        [self.playButton setImage:[UIImage imageNamed: @"_pause"] forState:UIControlStateNormal];
        
//        [self.stateImageView removeFromSuperview];
//        
//        NSMutableArray *animationImages = [[NSMutableArray alloc] init];
//        for (int i = 1; i<=6; ++i) {
//            NSString *str = [NSString stringWithFormat:@"w%d",i];
//            UIImage *image = [UIImage imageNamed:str];
//            [animationImages addObject:image];
//        }
//        self.stateImageView = [[UIImageView alloc] initWithFrame:CGRectMake(currentView.bounds.size.width-38, 30, 22, 22)];
//        self.stateImageView.backgroundColor = [UIColor blackColor];
//        self.stateImageView.userInteractionEnabled = NO;
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushPlayViewController)];
//        [self.stateImageView addGestureRecognizer:tap];
//        
//        self.stateImageView.animationImages = animationImages;
//        
//        self.stateImageView.animationDuration = 0.5;
//        self.stateImageView.animationRepeatCount = 0;
//        
//        [self.stateImageView startAnimating];
//        [self.view.window.];
    }else {
        //[self.stateImageView removeFromSuperview];
    }
}
-(void) audioPlayer:(AudioPlayer*)audioPlayer didEncounterError:(AudioPlayerErrorCode)errorCode{
    
}
-(void) audioPlayer:(AudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId{
    
}
-(void) audioPlayer:(AudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId{
    
}
//播放结束
-(void) audioPlayer:(AudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(AudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    self.isPlaying = NO;
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.playButton setImage:[UIImage imageNamed: @"_play"] forState:UIControlStateNormal];
}


@end
